﻿// The MIT License (MIT)
// Copyright (c) 2014 Grégory Ghez
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

namespace JenkinsController
{
    using System.Globalization;
    using System.Windows;
    using System.Windows.Threading;
    using Common.Logging;
    using Framework;
    using GalaSoft.MvvmLight.Messaging;
    using Jenkins.Core;
    using Microsoft.Practices.ServiceLocation;
    using Microsoft.Practices.Unity;
    using Model;
    using View;
    using ViewModel;

    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private static readonly ILog Logger = LogManager.GetCurrentClassLogger();

        protected override void OnStartup(StartupEventArgs e)
        {
            this.DispatcherUnhandledException += this.OnDispatcherUnhandledException;

            var container = new UnityContainer();
            var locator = new UnityServiceLocator(container);
            ServiceLocator.SetLocatorProvider(() => locator);

            // Service
            container.RegisterInstance(new CollectionHelper());
            container.RegisterInstance(Messenger.Default);
            container.RegisterInstance<IJenkinsRestClient>(new JenkinsRestFactory().GetClient());
#if DEMO
            container.RegisterInstance<IDataService>(new DemoDataService());
#else
            container.RegisterType<IDataService, DataService>(new ContainerControlledLifetimeManager());
#endif

            // View
            container.RegisterType<MainView>(new ContainerControlledLifetimeManager());
            container.RegisterType<ServerManagerView>();
            container.RegisterType<AboutView>();
            container.RegisterType<ChangeSetView>();
            container.RegisterType<LogsView>();
            container.RegisterType<JobView>();

            // ViewModel
            container.RegisterType<MainViewModel>(new ContainerControlledLifetimeManager());
            container.RegisterType<ServerManagerViewModel>(new ContainerControlledLifetimeManager());
            container.RegisterType<ChangeSetViewModel>();
            container.RegisterType<JobViewModel>();
            container.RegisterType<LogsViewModel>();

            // Messenger messages handling
            Messenger.Default.Register<WindowMessage<ServerManagerView>>(this, OnWindowMessageReceived);
            Messenger.Default.Register<WindowMessage<MainView>>(this, OnWindowMessageReceived);
            Messenger.Default.Register<WindowMessage<AboutView>>(this, OnWindowMessageReceived);
            Messenger.Default.Register<JobMessage>(this, OnJobMessageReceived);
            Messenger.Default.Register<ChangeSetMessage>(this, OnChangeSetMessageReceived);
            Messenger.Default.Register<LogsMessage>(this, OnLogsMessageReceived);

            this.MainWindow = container.Resolve<MainView>();

            base.OnStartup(e);
        }

        private void OnJobMessageReceived(JobMessage msg)
        {
            var view = ServiceLocator.Current.GetInstance<JobView>();
            ((JobViewModel)view.DataContext).Job = msg.Job;
            view.Show();
        }

        private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            Logger.Error(CultureInfo.InvariantCulture, m => m("Unhandled dispatcher exception."), e.Exception);
        }

        private static void OnChangeSetMessageReceived(ChangeSetMessage msg)
        {
            var view = ServiceLocator.Current.GetInstance<ChangeSetView>();
            ((ChangeSetViewModel)view.DataContext).Build = msg.Build;
            view.Show();
        }

        private static void OnLogsMessageReceived(LogsMessage msg)
        {
            var view = ServiceLocator.Current.GetInstance<LogsView>();
            ((LogsViewModel)view.DataContext).Build = msg.Build;
            view.Show();
        }

        private static void OnWindowMessageReceived<TView>(WindowMessage<TView> msg) where TView : Window
        {
            var view = ServiceLocator.Current.GetInstance<TView>();
            view.Show();
        }
    }
}